//
//  UserAccount.swift
//  DSWeibo
//
//  Created by J on 16/4/17.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SVProgressHUD

class UserAccount: NSObject,NSCoding {

    
    var access_token: String?
    var uid: String?
    var expires_Date: NSDate?
    var avatar_large: String?
    var screen_name: String?


    /// 保存用户过期时间
    var expires_in : NSNumber?{
        didSet{ //需要调用set方法才会走 直接赋值不行
            //根据过期秒数生成过期时间
            expires_Date = NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
        }
    }
    
    override init() {
        
    }
    
    init(dic:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("\(key):\(value!)")
    }
    
    
    
    override var description: String{
        let properties = ["access_token","expires_in","uid","expires_Date"]
        let dic = self.dictionaryWithValuesForKeys(properties)
        return "\(dic)"
    }
    
    func loadUserInfo(finished:(account:UserAccount?,error:NSError?)->()){
        assert(access_token != nil,"没有授权")
        
        let path = "2/users/show.json"
        let paramters = ["access_token":access_token!,"uid":uid!]
        NetWorkTools.shareNetWorkTools().GET(path, parameters: paramters, success: { (task:NSURLSessionDataTask, result:AnyObject?) in
            
            if let dict = result as?[String: AnyObject]{
                self.avatar_large = dict["screen_name"] as?String
                self.avatar_large = dict["avatar_large"] as?String
                finished(account: self, error: nil)
            }
            
            
            SVProgressHUD.showInfoWithStatus("网络不给力...", mastType: SVProgressHUDMaskType.Black)
            
            
            finished(account: nil, error: nil)
        }) { (task:NSURLSessionDataTask?, error:NSError) in
            
            SVProgressHUD.showInfoWithStatus("网络不给力...", mastType: SVProgressHUDMaskType.Black)
            finished(account: nil, error: nil)
        }


        
    }
    
    
    static var account: UserAccount?
    class func loadAccount()-> UserAccount?{
        
        if account != nil{
            return account
        }
        //2.加载授权模型
        account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cache()) as?UserAccount
        //3.判断授权是否过期
        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
       
        return nil//已经过期

        }
        
        return account

    }

    
    //归档
    func saveArchiver(){
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cache())
    }
    
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(expires_Date, forKey: "screen_name")
        aCoder.encodeObject(expires_Date, forKey: "avatar_large")


    }
    
  
    //解归档
    required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("expires_Date") as? String
        uid = aDecoder.decodeObjectForKey("screen_name") as? String
        uid = aDecoder.decodeObjectForKey("avatar_large") as? String

    }
    
    
    class func userLogin() -> Bool{
        return UserAccount.loadAccount() != nil
    }
    
    
    
    
}
